<style>
    .companyFormPhotos{
        /* margin-left:140px; */
        line-height: 38px;
        float: left;
    }
    .companyFormPhotos img{
        cursor: pointer;
        height: 38px;
        width: auto;
        max-width: 200px;
    }
    #warehouseOrderForm .layui-form-label {
        width: 110px;
    }

    #warehouseOrderForm .layui-input-block {
        margin-left: 140px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">订单编号</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="orderCode" class="layui-input" type="text" placeholder="请输入产品名称" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="warehouseOrderBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="warehouseOrderTable" lay-filter="warehouseOrderTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="warehouseOrderTableBar">

    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="info">详情</a>
    {{#  if(d.buyerCustomerId ==  d.loginCustomerId &&  d.buyerConfirm == 0){}}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="buyerConfirm">买家确定</a>
    {{# }}}
    {{#  if(d.sellerCustomerId ==  d.loginCustomerId &&  d.sellerConfirm == 0){}}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="sellerConfirm">卖家确定</a>
    {{# }}}
    {{#  if(d.loginCustomerId == 0 && d.transferStatus == 0){}}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="systemConfirm">管理员确认</a>
    {{# }}}
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="warehouseOrderForm">
    <form lay-filter="warehouseOrderForm" class="layui-form model-form">
        <div class="open-auto">
            <div class="layui-form-item layui-row">
                <input name="id" type="hidden"/>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">出售方客户</label>
                    <div class="layui-input-block">
                        <select id="sellerCustomerId" name="sellerCustomerId" lay-filter="sellerCustomerId"
                                lay-verify="required" required></select>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">出售方客户编号</label>
                    <div class="layui-input-block">
                        <input id="sellerCustomer" name="sellerCustomer" type="text" class="layui-input" disabled />
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">出售方客户联系人</label>
                    <div class="layui-input-block">
                        <input type="hidden" id="sellerCustomerUserName" name="sellerCustomerUserName" />
                        <select id="sellerCustomerUser" name="sellerCustomerUser" lay-filter="sellerCustomerUser"
                                lay-verify="required" required></select>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">出售方客户电话</label>
                    <div class="layui-input-block">
                        <input id="sellerCustomerPhone" name="sellerCustomerPhone" type="text" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-row">
                <div class="layui-form-item layui-row">
                    <input name="id" type="hidden"/>
                    <div class="layui-col-xs3">
                        <label class="layui-form-label">购买方客户</label>
                        <div class="layui-input-block">
                            <select id="buyerCustomerId" name="buyerCustomerId" lay-filter="buyerCustomerId"
                                    lay-verify="required" required></select>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <label class="layui-form-label">购买方客户编号</label>
                        <div class="layui-input-block">
                            <input id="buyerCustomer" name="buyerCustomer" type="text" class="layui-input" disabled />
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <label class="layui-form-label">购买方客户联系人</label>
                        <div class="layui-input-block">
                            <input type="hidden" id="buyerCustomerUserName" name="buyerCustomerUserName" />
                            <select id="buyerCustomerUser" name="buyerCustomerUser" lay-filter="buyerCustomerUser"
                                    lay-verify="required" required></select>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <label class="layui-form-label">购买方客户电话</label>
                        <div class="layui-input-block">
                            <input id="buyerCustomerPhone" name="buyerCustomerPhone" type="text" class="layui-input" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item tableContent">
                <button class="layui-btn" type="button" id="btnAddWarehouseProduct">添加物料</button>
                <table class="layui-table" id="warehouseProductFormTable"
                       lay-filter="warehouseProductFormTable"></table>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="warehouseOrderFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>
<script type="text/html" id="warehouseProductFormTableBar">
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin','upload','tableTreeDj','config','laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;
        var laydate = layui.laydate;


        // 渲染表格
        var insTb = table.render({
            elem: '#warehouseOrderTable',
            url: config.base + 'warehouse/warehouse/admin/transferOrder/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'}
                ,{field: 'transferCode', title: '过户订单编号', align: 'center'}
                ,{field: 'sourceDesc',title: '数据来源', align: 'center'}
                ,{field: 'sellerCustomerName', title: '出售客户名称', align: 'center'}
                ,{field: 'buyerCustomerName', title: '购买客户名称' , align: 'center'}
                ,{field: 'totalProduct', title: '过户件数' , align: 'center'}
                ,{field: 'transfer_time', title: '过户时间' , align: 'center'}
                ,{field: 'sellerConfirmDesc', title: '出售客户确认状态' , align: 'center'}
                ,{field: 'buyerConfirmDesc', title: '购买客户确认状态' , align: 'center'}
                ,{field: 'transferStatusDesc', title: '订单状态' , align: 'center'}
                ,{align: 'center', toolbar: '#warehouseOrderTableBar', title: '操作', width: 500, fixed: 'right'}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                // var menuButton = config.getMenuButton(location.hash);
                // if(menuButton.indexOf("搜索") == -1){
                //     $('.layui-form.toolbar').remove();
                // }
                // if(menuButton.indexOf("修改") == -1){
                //     $("[lay-event='edit']").remove();
                // }
                // if(menuButton.indexOf("删除") == -1){
                //     $("[lay-event='del']").remove();
                // }
            }
        });

        // 工具条点击事件
        table.on('tool(warehouseOrderTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'info') { //详情
                data.sellerCustomer = data.sellerCustomerId;
                data.buyerCustomer  = data.buyerCustomerId;
                data.sellerCustomerUser = data.sellerContactId;
                data.buyerCustomerUser = data.buyerContactId;
                showEditModel(data);
            }else if (obj.event === 'withdraw') { // 撤回
                updateStatus(data,0,);
            } else if (obj.event === 'sellerConfirm') { // 确认
                updateStatus(data,1,'seller');
            }else if(obj.event === 'buyerConfirm'){
                updateStatus(data,1,'buyer');
            }else if(obj.event === 'systemConfirm'){
                updateStatus(data,1,'systemConfirm');
            }
        });
        function info(data){
        }

        // 修改订单状态
        function updateStatus(data,status,type) {
            admin.req('warehouse/warehouse/admin/transferOrder/updateStatus', {id:data.id,status:status,type:type}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('warehouseOrderTable',{});
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'GET');
            layer.close(index);
        }

        //监听排序
        table.on('sort(warehouseOrderTable)', function(obj){
            table.reload('warehouseOrderTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#warehouseOrderBtnAdd').click(function () {
            showEditModel();
        });


        // 显示编辑弹窗
        function showEditModel(data) {
            admin.formOpen({
                type: 1,
                area: ['90%', '80%'],
                offset: '65px',
                title: data ? '修改过户订单' : '添加过户订单',
                content: $('#warehouseOrderForm').html(),
                success: function () {

                    //客户信息
                    admin.reqSync('enterprise/sell/admin/customersInfo/list', {'limit':9999}, function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            loadSelectHtml(res.data, "请选出售客户信息", "sellerCustomerId",1);
                            if(config.getUser().clientId === 'warehouse'){
                                $('#sellerCustomerId').prop('disabled', true);
                                $('#sellerCustomer').val(config.getUser().selCustomerId);
                                let dataObj ={};
                                dataObj.id = config.getUser().selCustomerId;
                                userNameSelect(dataObj,"sellerCustomerUser")
                            }
                            loadSelectHtml(res.data, "请选购买客户信息", "buyerCustomerId",1);
                        }
                    }, 'GET');
                    //设备型号下拉操作
                    form.on('select(sellerCustomerId)', function (data) {
                        if (data.value === '') {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr('data'));
                            $("#sellerCustomer").val(dataObj.id)
                            userNameSelect(dataObj,"sellerCustomerUser")
                        }
                    });
                    form.on('select(buyerCustomerId)', function (data) {
                        if (data.value === '') {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr('data'));
                            $("#buyerCustomer").val(dataObj.id)
                            userNameSelect(dataObj,"buyerCustomerUser")
                        }
                    });
                    if(data){
                        let buyerDataObj = {};
                        buyerDataObj.id = data.buyerCustomerId;
                        let sellerDataObj = {};
                        sellerDataObj.id = data.sellerCustomerId;
                        userNameSelect(buyerDataObj,"buyerCustomerUser");
                        userNameSelect(sellerDataObj,"sellerCustomerUser");
                        $("#buyerCustomerPhone").val(data.buyerPhone);
                        $("#sellerCustomerPhone").val(data.sellerPhone);

                        admin.req('warehouse/warehouse/productInventory/list', {transferId:data.id}, function (res) {
                            if (res.code === 200) {
                                table.reload('warehouseProductFormTable', {
                                    data: res.data  // 设置新的数据
                                });
                            }
                        });


                    }
                    function userNameSelect(data,type) {
                        admin.reqSync('enterprise/sell/admin/contactInfo/list?page=1&limit=9999', {selCustomerId:data ? data.id:null}, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选联系人信息", type,2);
                            }
                        }, 'GET');
                    }
                    form.on('select(sellerCustomerUser)', function (data) {
                        if (data.value === '') {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr('data'));
                            $("#userName").val(dataObj.id)
                            $("#sellerCustomerPhone").val(dataObj.telephone)
                        }
                    });
                    form.on('select(buyerCustomerUser)', function (data) {
                        if (data.value === '') {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr('data'));
                            $("#userName").val(dataObj.id)
                            $("#buyerCustomerPhone").val(dataObj.telephone)
                        }
                    });


                    parentData.data = data;
                    const nowData = {...parentData}
                    table.render({
                        elem: '#warehouseProductFormTable',
                        page: false,
                        limit: 999999,
                        data: [],
                        cols: [[
                            {type: 'numbers', title: '序号', fixed: 'left'}
                            ,{field: 'sysBundleCode', title: '系统捆包码', align: 'center'}
                            ,{field: 'userBundleCode',title: '用户捆包码', align: 'center'}
                            ,{field: 'productCode', title: '货主料号' , align: 'center'}
                            ,{field: 'productProducer', title: '厂家', align: 'center'}
                            ,{field: 'productVariety', title: '品种' , align: 'center'}
                            ,{field: 'productSpecCode', title: '规格' , align: 'center'}
                            ,{field: 'productMark', title: '牌号' , align: 'center'}
                            ,{field: 'productBrand', title: '品牌' , align: 'center'}
                            ,{field: 'productMainUnit', title: '计量单位' , align: 'center'}
                            ,{field: 'netWeight', title: '标准毛重' , align: 'center'}
                            ,{field: 'grossWeight', title: '标准净重' , align: 'center'}
                            ,{
                                align: 'center',
                                fixed: 'right',
                                toolbar: '#warehouseProductFormTableBar',
                                title: '操作',
                                hide: nowData.eventName === 'view'
                            }
                        ]],
                        error: function () {
                            console.log('请求失败');
                        }
                    });

                    form.val('warehouseOrderForm', data);

                    // 表单提交事件
                    form.on('submit(warehouseOrderFormSubmit)', function (d) {
                        const formData = {...d.field}
                        formData.warehouseTransferOrderDetail = table.cache['warehouseProductFormTable']
                        layer.load(2);
                        admin.req(data ? 'warehouse/warehouse/admin/transferOrder/update' : 'warehouse/warehouse/admin/transferOrder/add', JSON.stringify(formData), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('warehouseOrderTable',{});
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST', false, "application/json");
                    });
                    $('#btnAddWarehouseProduct').click(function () {
                        admin.formOpen({
                            area: '90%',
                            offset: '50px',
                            title: '配置物料信息',
                            path: 'components/warehouse/product/customerProductListForm.html',
                            success: function () {
                                parentData.cacheList = [...table.cache['warehouseProductFormTable']]
                                parentData.customerId = $("#sellerCustomer").val();
                                console.log(parentData.cacheList)
                                if (parentData.cacheList.length > 0) {
                                    parentData.notInListIds = table.cache['warehouseProductFormTable'].map(v => {
                                        // if (v.id) return v.id
                                        if (v.productDetailId) return v.productDetailId
                                    }).join(',')
                                } else {
                                    parentData.notInListIds = ''
                                }
                            },
                            end: function () {
                                if (childData.list) {
                                    const newData = childData.list || []
                                    newData.forEach(v => {
                                        v.productCategory = v.productTypeId
                                        v.productName = v.skuName
                                        v.specifications = v.skuSpec
                                        v.unitName = v.mainUnitName
                                        v.remark = ''
                                        v.rate = (v.taxRate === '' || !v.taxRate) ? '0' : v.taxRate
                                        v.taxPrice = v.currentCostPrice
                                    })
                                    const oldData = table.cache['warehouseProductFormTable']
                                    const list = [...oldData, ...newData]
                                    table.reload('warehouseProductFormTable', {
                                        data: list  // 设置新的数据
                                    });
                                }

                            }
                        })
                    })
                    table.on('tool(warehouseProductFormTable)', function (obj) {
                        var d = obj.data;  // 获取当前行的数据
                        var layEvent = obj.event;  // 获取事件名（edit 或 del）
                        if (obj.tr) {
                            obj.tr.on('click', function (e) {
                                e.preventDefault(); // 防止默认行为
                            });
                        }
                        if (layEvent == 'del') {
                            const index = $(obj.tr[0]).data('index')
                            let list = table.cache['warehouseProductFormTable'].filter(v => {
                                return v['LAY_TABLE_INDEX'] != index
                            })
                            table.reload('warehouseProductFormTable', {
                                data: list
                            })
                        }
                    });
                }
            });
        }


        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type == 1) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' ${data[i].id === config.getUser().selCustomerId && htmltarget ==='sellerCustomerId' ? 'selected' : ''}>${data[i].customerName}</option>`;
                } else if (type == 2){
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].name}</option>`;
                } else if (type == 3){
                    html += `<option value='${data[i].id}' id='${data[i].id}'>${data[i].producerName}</option>`;
                }else {
                    html += `<option value='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].name}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

        // 上传图片
        function uploadImg(_elem, pathId, inputId) {
            upload.render({
                elem: '#' + _elem
                , url: config.upload_url + 'uploadFile'
                , data: {}
                , accept: 'file'
                , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                , headers: { Authorization: 'Bearer ' + config.getToken() }
                , done: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg || "上传成功", { icon: 1 });
                        let imagUrl = res.data.url;
                        $('#' + pathId).html('<img src="' +imagUrl + '"/>');
                        $('#' + inputId).val(imagUrl);
                    } else if (res.code == 502) {
                        return location.replace('member/login.html');
                    } else {
                        layer.msg(res.msg || "上传失败", { icon: 2 });
                    }
                }
            });
        }
    });
</script>